package org.jeecg.modules.xl.shopcart.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.xl.common.XlLogUtil;
import org.jeecg.modules.xl.mpapi.vo.ShopCartVo;
import org.jeecg.modules.xl.order.entity.XlCustomerOrde;
import org.jeecg.modules.xl.order.service.IXlCustomerOrdeService;
import org.jeecg.modules.xl.shengfutong.config.ShengftConf;
import org.jeecg.modules.xl.shengfutong.request.PreUnifieAppletdorderRequest;
import org.jeecg.modules.xl.shengfutong.response.PreUnifieAppletdorderPayInfo;
import org.jeecg.modules.xl.shengfutong.response.PreUnifieAppletdorderResponse;
import org.jeecg.modules.xl.shengfutong.util.ShengFuTongSignUtil;
import org.jeecg.modules.xl.shopcart.entity.XlShopcart;
import org.jeecg.modules.xl.shopcart.mapper.XlShopcartMapper;
import org.jeecg.modules.xl.shopcart.service.IXlShopcartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author deco
 * @create 2025-03-03
 */
@Service
public class XlShopcarServiceImpl extends ServiceImpl<XlShopcartMapper, XlShopcart> implements IXlShopcartService {
    @Resource
    private IXlCustomerOrdeService xlCustomerOrdeService;
    @Override
    public Result addShopcart(XlShopcart shopcart) {
        //判断新增 还是 调整梳理
        QueryWrapper<XlShopcart> shopcartQueryWrapper = new QueryWrapper<>();
        shopcartQueryWrapper.eq("store_code", shopcart.getStoreCode());
        shopcartQueryWrapper.eq("upc_code",shopcart.getUpcCode());
        XlShopcart xlShopcart = baseMapper.selectOne(shopcartQueryWrapper);
        if(ObjectUtil.isNotEmpty(xlShopcart)){
            //如果不为空，说明是调整购物车数量
            xlShopcart.setQuantity(shopcart.getQuantity());
            baseMapper.updateById(xlShopcart);
        }else{
            //是购物车里的新品种
            baseMapper.insert(shopcart);
        }
        return Result.OK("添加成功");
    }

    @Override
    public Result removeShopcartItem(XlShopcart shopcart) {
        QueryWrapper<XlShopcart> shopcartQueryWrapper = new QueryWrapper<>();
        shopcartQueryWrapper.eq("store_code", shopcart.getStoreCode());
        shopcartQueryWrapper.eq("upc_code",shopcart.getUpcCode());
        XlShopcart xlShopcart = baseMapper.selectOne(shopcartQueryWrapper);
        if(ObjectUtil.isNotEmpty(xlShopcart)){
            baseMapper.deleteById(xlShopcart.getId());
            return Result.ok("删除成功");
        }else{
            return Result.error("删除成功");
        }

    }

    @Override
    public Result<JSONObject> clearCart(String storeCode) {
        QueryWrapper<XlShopcart> shopcartQueryWrapper = new QueryWrapper<>();
        shopcartQueryWrapper.eq("store_code", storeCode);
        baseMapper.delete(shopcartQueryWrapper);
        return Result.OK("清除购物车成功！");
    }

    @Override
    public List<ShopCartVo> getCart(String storeCode) {
        return baseMapper.getCart(storeCode);
    }


    @Autowired
    private XlLogUtil xlLogUtil;
    @Override
    public Result<Object> submitOrder(String storeCode, String orderNote) {
        QueryWrapper<XlShopcart> shopcartQueryWrapper = new QueryWrapper<>();
        shopcartQueryWrapper.eq("store_code", storeCode);
        //查询购物所有的商品
        List<XlShopcart> shopcarts = baseMapper.selectList(shopcartQueryWrapper);
        if(ObjectUtil.isEmpty(shopcarts)){
            return Result.error("提交失败，购物车为空");
        }
        //保存订单
        XlCustomerOrde xlCustomerOrde = xlCustomerOrdeService.submitOrder(storeCode,shopcarts,orderNote);
        xlLogUtil.insertLog(xlCustomerOrde.getOrderCode(),"提交","小程序购物车提交订单",new Date(),"待提交","待支付");
        if(ObjectUtil.isEmpty(xlCustomerOrde)||ObjectUtil.isEmpty(xlCustomerOrde.getId())){
            return Result.error("订单提交失败");
        }else{
            //清除购物车
            this.clearCart(storeCode);
            Result result = new Result();
            result.setSuccess(true);
            result.setMessage("订单提交成功");
            Map map = new HashMap<>();
            map.put("orderCode",xlCustomerOrde.getOrderCode());
            map.put("totalAmount",xlCustomerOrde.getTotalAmount());
            map.put("receiveInfo",xlCustomerOrde.getReceiptName()+" "+ xlCustomerOrde.getReceiptPhone()+ " "+ xlCustomerOrde.getReceiptAddress());
             result.setResult(map);
             return result;
        }

    }

    @Override
    public PreUnifieAppletdorderPayInfo preUnifieAppletdorder(String orderCode) throws Exception {
        QueryWrapper<XlCustomerOrde> wrapper = new QueryWrapper<>();
        wrapper.eq("order_code",orderCode);
        XlCustomerOrde xlCustomerOrde = xlCustomerOrdeService.getOne(wrapper);
        if(ObjectUtil.isAllEmpty(xlCustomerOrde,xlCustomerOrde.getTotalAmount())){
            return null;
        }
        //PreUnifieAppletdorderRequest request = PreUnifieAppletdorderRequest.buildPreUnifieAppletdorderRequest(xlCustomerOrde.getOrderCode(), 1,xlCustomerOrde.getStoreCode(),xlCustomerOrde.getStoreName());//测试阶段使用分
        BigDecimal ss = BigDecimal.valueOf(xlCustomerOrde.getTotalAmount()*100);
        ss.setScale(0,BigDecimal.ROUND_HALF_UP);

        PreUnifieAppletdorderRequest request =
                PreUnifieAppletdorderRequest.buildPreUnifieAppletdorderRequest(xlCustomerOrde.getOrderCode(),ss.intValue(),xlCustomerOrde.getStoreCode(),xlCustomerOrde.getStoreName());//元转为分
        request.setPageUrl("pages/order-detail/orderDetail");
        String sign = ShengFuTongSignUtil.sign(BeanUtil.beanToMap(request), ShengftConf.PRIVATEKEY);// WalletSignUtils.sign(request, AggreConfig.PRIVATEKEY, SignType.RSA, new String[]{"sign"});
        request.setSign(sign);
        System.out.println("PreUnifieAppletdorderResponse request : "+JSON.toJSONString(request));
        String resultJsonTemp = HttpUtil.post(ShengftConf.URL.concat("/pay/preUnifieAppletdorder"), JSON.toJSONString(request));

        System.out.println("PreUnifieAppletdorderResponse response : "+resultJsonTemp);
        PreUnifieAppletdorderResponse response = JSONUtil.toBean(resultJsonTemp, PreUnifieAppletdorderResponse.class);
        //boolean verify = WalletSignUtils.verify(response, AggreConfig.PUBLICKEY, response.getSign(), SignType.RSA, new String[]{"sign"});
        //System.out.println("验证签名结果："+verify);
        if (StringUtils.equalsIgnoreCase(response.getResultCode(), "SUCCESS")){
            xlLogUtil.insertLog(xlCustomerOrde.getOrderCode(),"支付","小程序支付成功",new Date(),"待支付","待审核");
            return JSONUtil.toBean(response.getPayInfo(), PreUnifieAppletdorderPayInfo.class);
        }else{
            //异常信息
            System.out.println("payInfo:"+response.getErrorCode()+" |"+response.getErrorCodeDes());
            return null;
        }
    }
}
